<?php
/**
 * created by zzy
 * date: 2017/10/24 9:28
 */

namespace App\Http\Admin\Process\Controllers;

use App\Eloquent\Ygt\ProcessFieldCategory;
use App\Engine\Func;
use Framework\BaseClass\Http\Admin\Controller;
use App\Eloquent\Ygt\Process;
use App\Eloquent\Ygt\ProcessProcess;
use App\Eloquent\Ygt\ProcessField;
use App\Eloquent\Ygt\ProcessFieldRelation;
use App\Eloquent\Ygt\ProcessFieldRelationSelect;
use App\Eloquent\Ygt\ProcessFieldRelationUnit;

class SettingController extends Controller
{
    public function fieldEdit()
    {
        $admin_user         = request()->user('admin')->toArray();
        $company_id         = $admin_user['company_id'];

        $process_id         = request('id');

        if (request()->isMethod('post')) {
            try {
                $id_arr         = request('id_arr');
                if( !empty($id_arr) ){

                    $collection         = ProcessFieldRelation::withTrashed()->where( 'process_id', $process_id )->get();
                    $all_field_list     = $collection->toArray();
                    $del_arr            = $field_arr = [];
                    foreach( $all_field_list as $key=>$val )
                    {
                        if( $val['deleted_at'] > 0 ){
                            $del_arr[]      = $val['field_id'];
                        } else {
                            $field_arr[]    = $val['field_id'];
                        }
                    }
                    $update_del_arr     = array_intersect( $del_arr, $id_arr );
//                    var_dump($update_del_arr);exit;
                    if( $update_del_arr )
                    {
                        ProcessFieldRelation::withTrashed()->where('process_id',$process_id)
                            ->whereIn( 'field_id',$update_del_arr )->restore();
                    }
                    $new_id_arr         = array_diff( $id_arr, $del_arr );
                    $new_del_arr        = array_diff( $field_arr, $new_id_arr );
//                    var_dump($new_del_arr);exit;
                    if( $new_del_arr )
                    {
                        $where          = ['process_id'=>$process_id, 'field_id'=>['in',$new_del_arr]];
                        ProcessFieldRelation::del($where);
                    }
                    $new_field_arr      = array_diff( $new_id_arr, $field_arr );
//                    var_dump($new_field_arr);exit;
                    $process_where      = ['company_id'=>$company_id];
                    $process_list       = Process::getList( $process_where, 'id' );
                    $company_process_id_arr = [];
                    foreach( $process_list as $key=>$val )
                    {
                        $val_id         = $val->id;
                        if( $val_id != $process_id )
                        {
                            $company_process_id_arr[]   = $val->id;
                        }
                    }
                    foreach( $new_field_arr as $key=>$val ){
                        $data           = [
                            'process_id'=>$process_id, 'field_id'=>$val,
                        ];
                        $insert_id      = ProcessFieldRelation::insertOneData( $data, 'id' );
                        $where          = [
                            'field_id'=>$val, 'process_id'=>['in',$company_process_id_arr]
                        ];
                        $old_relation   = ProcessFieldRelation::getInfo( $where );
                        if( $old_relation )
                        {
                            $old_relation_id    = $old_relation->id;
                            $where              = ['relation_id'=>$old_relation_id];
                            $select_list        = ProcessFieldRelationSelect::getList( $where,'','','',['pid','asc'] )->toArray();
                            $v_pid_arr          = [];
                            foreach( $select_list as $k=>$v )
                            {
                                $v_id           = $v['id'];
                                $v_pid          = $v['pid'];
                                if( $v_pid == 0 )
                                {
                                    $data           = [
                                        'relation_id'=>$insert_id, 'pid'=>0,
                                        'title'=>$v['title'], 'title_type'=>$v['title_type']
                                    ];
                                    $new_pid        = ProcessFieldRelationSelect::insertOneData( $data,'id' );
                                    $v_pid_arr[$v_id]   = $new_pid;
                                }
                            }
                            if( $v_pid_arr )
                            {
                                foreach( $select_list as $k=>$v )
                                {
                                    $v_pid          = $v['pid'];
                                    if( $v_pid != 0 && isset($v_pid_arr[$v_pid]) )
                                    {
                                        $pid            = $v_pid_arr[$v_pid];
                                        $data           = [
                                            'relation_id'=>$insert_id, 'pid'=>$pid,
                                            'title'=>$v['title'], 'title_type'=>$v['title_type']
                                        ];
                                        ProcessFieldRelationSelect::insertOneData( $data );
                                    }
                                }
                            }
                        }
                    }
                }
                Process::updateOneData( ['id'=>$process_id], ['is_last'=>1] );
                return $this->ajaxSuccess('成功');
            } catch (\DebugError $e) {
                return $this->ajaxFail($e->getMessage());
            }

        } else {
            $where          = ['id'=>$process_id];
            $info           = Process::getInfo( $where );
            $info_field_list= Process::getFieldListByProcessId($process_id);
            $info_field_arr = [];
            foreach ( $info_field_list as $key=>$val ){
                $info_field_arr[]   = $val['id'];
            }
//            $type_list      = ProcessField::getTypeList(5);
            $where              = ['company_id'=>$company_id];
            $fieldCategoryList	= ProcessFieldCategory::getRows($where)->toArray();
            $type_list          = Func::getIdTitleByType( $fieldCategoryList, 5 );

            //$lists          = ProcessField::getList('')->toArray();
            $lists          = ProcessField::getCompanyFieldList( $company_id );
            $listsArr       = collect($lists)->groupBy('type')->toArray();
            $data           = [];
            foreach($listsArr as $key=>$val)
            {
                $title      = '不存在-'.$key;
                foreach( $type_list as $k=>$v )
                {
                    if($key == $v['id'])
                    {
                        $title  = $v['title'];
                    }
                }
                $temp           = [
                    'id'=>$key, 'title'=>$title, 'data'=>$val
                ];
                $data[]         = $temp;
            }
//            foreach( $type_list as $key=>$val )
//            {
//                $type_id                = $val['id'];
//                $type_title             = $val['title'];
//                $type_data              = [];
//                foreach( $lists as $k=>$v )
//                {
//                    if( $type_id == $v['type'] )
//                    {
//                        $type_data[]    = $v;
//                    }
//                }
//                $arr        = [
//                    'id'=>$val['id'], 'title'=>$type_title, 'data'=>$type_data
//                ];
//                $data[]     = $arr;
//            }
            return $this->view('filed-edit', compact( 'info', 'info_field_arr','data' ) );
        }
    }
    public function fieldManage()
    {
        $adminUser          = request()->user('admin')->toArray();
        $companyId          = $adminUser['company_id'];

        $processId          = request('id');
        $where              = ['id'=>$processId];
        $process            = Process::getInfo($where)->toArray();
        $collection         = ProcessFieldRelation::getFieldListByProcessId( $companyId, $processId );
        $lists              = $collection->toJson();
        $lists              = str_replace('"', "'",$lists);
        $fieldTypeList      = ProcessField::getFieldTypeList( 4 );
        $data               = ['process'=>$process,'lists'=>$lists];
        $jsonData           = ['field_type_list'=>$fieldTypeList];
        return $this->view('field-manage',compact('data','jsonData') );
    }
    public function fieldManageEdit()
    {
        $params             = $this->requestJson();
        $relation_id        = $params['relation_id'];
        if( !$relation_id ){
            return $this->ajaxSuccess('失败');
        }
        $is_must            = $params['is_must'];
        $orderby            = $params['orderby'];
        $where              = ['id'=>$relation_id];
        $data               = ['is_must'=>$is_must,'orderby'=>$orderby];
        $result             = ProcessFieldRelation::updateOneData( $where, $data );
        if( $result ){
            return $this->ajaxSuccess('成功');
        } else {
            return $this->ajaxFail('失败');
        }
    }
    public function fieldManageDelete(){
        return $this->ajaxFail('暂不开启删除');
    }
    public function fieldSet()
    {
        $admin_user         = request()->user('admin')->toArray();
        $company_id         = $admin_user['company_id'];

        $relation_id         = request('relation_id');
        if (request()->isMethod('post')) {

            $title_type      = request('title_type','');
            $params          = $this->requestJson();
            $id              = isset($params['id']) ? $params['id'] : 0;
            $pid             = isset($params['pid']) ? $params['pid'] : 0;
            $title           = $params['title'];
            $isDefault       = isset($params['is_default']) ? $params['is_default'] : 0;
            if( !empty($title) ){
                if($isDefault == 1)
                {
                    $dafaultData    = ['is_default'=>0];
                    ProcessFieldRelationSelect::where('relation_id',$relation_id)->update($dafaultData);
                }
                $data           = [
                    'relation_id'=>$relation_id,'pid'=>$pid,
                    'title'=>$title,'title_type'=>$title_type,
                    'is_default'=>$isDefault
                ];
                if( $id ){
                    $where      = ['id'=>$id];
                    $result     = ProcessFieldRelationSelect::updateOneData( $where, $data );
                } else {
                    $result     = ProcessFieldRelationSelect::insertOneData( $data );
                }
                if( $result ){
                    return $this->ajaxSuccess('成功');
                } else {
                    return $this->ajaxFail('失败');
                }
            } else {
                return $this->ajaxFail('选项标题不能为空');
            }

        } else {

            $info                   = ProcessFieldRelation::getFieldInfoById( $company_id, $relation_id );
            $field_type             = $info->field_type;
            $where                  = ['id'=>$info->process_id];
            $process                = Process::getInfo( $where );

            $fields                 = 'id,pid,title,title_type,is_default';
            $select_list_collection = ProcessFieldRelationSelect::getList(['relation_id'=>$relation_id,],$fields);
            $select_list_arr        = $select_list_collection->toArray();
            $select_list            = $select_list2           = [];
            switch ($field_type)
            {
                case 14:
                    foreach( $select_list_arr as $key=>$val )
                    {
                        if( $val['title_type'] == '14s2' )
                        {
                            $select_list2[]     = $val;
                        } else {
                            $select_list[]      = $val;
                        }
                    }
                    break;
                default:
                    $select_list        = $select_list_arr;
            }
            $select_list    = json_encode($select_list);
            $select_list    = str_replace('"', "'",$select_list);
            $select_list2   = json_encode($select_list2);
            $select_list2   = str_replace('"', "'",$select_list2);

            $view_blade             = 'field-set';
            $info_field_type        = $info->field_type;
            $info_field_type_arr    = [11,14];
            if( in_array( $info_field_type, $info_field_type_arr ) ){
                $view_blade .= '-'.$info_field_type;
            }
            return $this->view($view_blade, compact( 'info', 'process', 'select_list','select_list2' ) );
        }
    }
    public function fieldSetDelete(){
        $id                 = request('id',0);
        if( $id ){
            $id_arr         = explode(',',$id);
            if( in_array( 0, $id_arr ) ){
                return $this->ajaxFail('失败0');
            }
            $where          = ['id'=>['in',$id_arr]];
            $del_result     = ProcessFieldRelationSelect::del($where);
            if( $del_result !== false ){
                $where          = ['pid'=>['in',$id_arr]];
                $del_result     = ProcessFieldRelationSelect::del($where);
                if( $del_result !== false ){
                    return $this->ajaxSuccess('成功');
                } else {
                    return $this->ajaxFail('失败2');
                }
            } else {
                return $this->ajaxFail('失败2');
            }
        } else {
            return $this->ajaxFail('失败3');
        }
    }
    public function processEdit()
    {
        $admin_user         = request()->user('admin')->toArray();
        $company_id         = $admin_user['company_id'];

        $process_id         = request('id');

        $info               = Process::getInfo(['id'=>$process_id],'id,title,is_last,company_id')->toArray();
        $where              = [
            'company_id' => $company_id, 'is_last' => ['!=', 0]
        ];
        $lists              = Process::getList($where,'id,title,is_last,company_id');
        $lists_arr          = $lists->toArray();
        $data               = ProcessProcess::setProcessData( $lists_arr );
//        foreach( $data as $key=>$val ){
//            print_r($val);
//            echo '<hr/>';
//        }exit;
        foreach( $data as $key=>$val ){
            if( $val['id'] == $process_id ){
                $info           = $val;
                unset( $data[$key] );
                continue;
            }
        }
//        print_r($info['sids']);exit;
        if (request()->isMethod('post')) {
            $id_arr                 = request('id_arr');
            $id_arr_son_ids         = [];
            foreach( $data as $key=>$val ){
                if( in_array( $val['id'], $id_arr ) ){
                    $id_arr_son_ids = array_merge($id_arr_son_ids, $val['all_sids']);
                }
            }

            $unique_arr             = array_unique($id_arr_son_ids);
            $diff_arr               = array_diff_assoc( $id_arr_son_ids, $unique_arr );
            if( empty( $diff_arr ) ){
                Process::updateOneData( ['id'=>$process_id], ['is_last'=>2] );
                $where              = ['process_id'=>$process_id];
                $del_result         = ProcessProcess::del( $where );
                if( $del_result !== false ){
                    foreach( $id_arr as $key=>$val ){
                        $data       = [ 'process_id'=>$process_id, 'son_process_id'=>$val ];
                        ProcessProcess::insertOneData($data);
                    }
                    return $this->ajaxSuccess('成功');
                } else {
                    return $this->ajaxFail('失败');
                }
                //return $this->ajaxSuccess('成功');
            } else {
                $message            = '';
                foreach( $data as $key=>$val ){
                    if( in_array( $val['id'], $diff_arr ) ){
                        $message    .= $val['title'].'--';
                    }
                }
                $message            .= '重复';
                return $this->ajaxFail($message);
            }
        } else {

            return $this->view('process-edit', compact('info', 'data'));
        }
    }
}
